import { Injectable } from '@angular/core';
import { ModalOptions, NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { EMPTY, Observable } from 'rxjs';
import { map, mergeMap, tap } from 'rxjs/operators';
import { AbstractForm } from '../../abstract/abstract-form';

@Injectable({
  providedIn: 'root'
})
export class CommonModalService {
  constructor(
    private nzModalService: NzModalService,
  ) { }

  create<V, T>(options: ModalOptions<V, T>) {
    const modalRef = this.nzModalService.create(options) as NzModalRef<V, T>;
    // 弹窗打开之后，订阅onSubmitted对弹窗进行关闭操作
    modalRef.afterOpen.pipe(
      map(() => modalRef.getContentComponent()),
      mergeMap(component => {
        if (component instanceof AbstractForm) {
          console.log('AbstractForm');
          return component.onSubmitted;
        }
        return EMPTY;
      }),
      tap(data => {
        modalRef.close(data);
      })
    ).subscribe();
    return modalRef;
  }

  createFormModal<V, T>({ nzTitle, nzContent, data, submit }: Pick<ModalOptions, 'nzTitle' | 'nzContent'>
  & { data: V, submit: (value: V) => Observable<T> }) {
    const modalRef: NzModalRef = this.create({
      nzTitle,
      nzContent,
      nzComponentParams: {
        data,
        submit: (value: V) => {
          modalRef.updateConfig({ nzOkLoading: true });
          return submit(value).pipe(
            tap(() => {
              modalRef.updateConfig({ nzOkLoading: false });
            })
          );
        }
      },
      nzOnOk(component) {
        if (component instanceof AbstractForm) {
          component.onSubmit().subscribe();
        }
        return false;
      }
    });
  }

}
